package filters

import (
	"fmt"
	"github.com/astaxie/beego/context"
)

func Cors(Ctx *context.Context) {
	if Ctx.Request.Method == "OPTIONS" {
		Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")                                       //允许访问源
		Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, DELETE, PATCH, PUT, OPTIONS") //允许post访问
		Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")             //header的类型
		Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
		Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
		Ctx.ResponseWriter.Header().Set("content-type", "application/json") //返回数据格式是json
		_, error := Ctx.ResponseWriter.Write([]byte("OK"))
		if error != nil {
			fmt.Println("CORS Failed")
		}
	} else {
		Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	}
}
